

#include "data_global.h"

extern pthread_mutex_t mutex_led;
extern pthread_cond_t  cond_led;

extern pthread_mutex_t mutex_fan;
extern pthread_cond_t  cond_fan;

extern pthread_mutex_t mutex_buzzer;
extern pthread_cond_t  cond_buzzer;

extern int msgid;
extern key_t key;

extern struct msg msgbuf;
extern unsigned char  cmd_led;
extern unsigned char  cmd_fan;
extern unsigned char  cmd_buzzer;

//处理CGI进程下发的请求（遍历消息队列）
void *pthread_client_request(void *arg)
{
	
	//创建消息队列
	if((key = ftok("tmp", 'g')) < 0){
		perror("ftok");
		return NULL;
	}
	//独占创建消息队列
	msgid = msgget(key, IPC_CREAT | IPC_EXCL | 0666);
	if(msgid == -1){
		if(errno == EEXIST){
			//消息队列已存在，直接获取
			msgid = msgget(key, 0666);
		}else{
			perror("msgget");
			return NULL;
		}
	}
	

	while(1){
		bzero(&msgbuf, sizeof(msgbuf));
		//0 表示阻塞接收消息 1L:接收消息类型为1的消息
		msgrcv(msgid, &msgbuf, sizeof(msgbuf) - sizeof(long), 1L, 0);
		printf("process-monitor  msgType : %d\n", msgbuf.msgtype);
		printf("process-monitor  msgText : %x\n", msgbuf.text[0]);
		switch(msgbuf.msgtype){
			case 1L:
				//控制LED亮灭
				pthread_mutex_lock(&mutex_led);
				cmd_led = msgbuf.text[0];
				pthread_cond_signal(&cond_led);
				pthread_mutex_unlock(&mutex_led);
				break;
			case 2L:
				//控制蜂鸣器亮灭
				pthread_mutex_lock(&mutex_buzzer);
				cmd_buzzer = msgbuf.text[0];
				pthread_cond_signal(&cond_buzzer);
				pthread_mutex_unlock(&mutex_buzzer);
				break;
			case 4L:
				//控制风扇开关
				pthread_mutex_lock(&mutex_fan);
				cmd_fan = msgbuf.text[0];
				pthread_cond_signal(&cond_fan);
				pthread_mutex_unlock(&mutex_fan);
				break;
			default:
				break;
		}
	}

}
